from Products.Five import BrowserView
from plone.app.multilingual.interfaces import ITranslationGroupLookup, ITranslationUtility

from Acquisition import aq_inner, aq_parent
from zope.component import getMultiAdapter, getUtility
from Products.statusmessages.interfaces import IStatusMessage
from plone.app.multilingual import MultilingualMessageFactory as _
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile

from Products.CMFCore.utils import getToolByName

# XXX: To Remove
# from Products.Archetypes.browser.edit import Edit

class TranslationForm(BrowserView):
    """Additional useful methods to render translation form view"""
# XXX: To Remove:
#    __call__ = ViewPageTemplateFile('translate_item.pt')

    def __init__(self, context, request):
        self.context = context
        self.request = request
        portal_state=getMultiAdapter((context, request), name="plone_portal_state")
        self.portal_url = portal_state.portal_url()
        self.group = ITranslationGroupLookup(self.context)
        
    def objToTranslate(self):
        defaultlang=getToolByName(self.context,'portal_languages').getDefaultLanguage()
        return self.group.getTranslation(defaultlang)
        
    def getTranslatedLanguages(self):
        return self.group.getTranslationLanguages()
        #TODO: Exclude actual language

    # XXX: To backcompatibility To remove if not used
    def mimetypesToRenderInTranslationForm(self):
        return ('text/html',)

    #def test(self, expr, statementTrue, statementFalse):
    #    if expr:
    #        return statementTrue
    #    else:
    #        return statementFalse

class BabelView(BrowserView):
    template = ViewPageTemplateFile('babel_view.pt')
    langchangeto = ''

    def __init__(self, context, request):
        self.context = context
        self.request = request
        self.group = ITranslationGroupLookup(self.context)
        
    def __call__(self):
        try:
            self.langchangeto=self.request["langchangeto"]
        except:    
            self.langchangeto=getToolByName(self.context,'portal_languages').getDefaultLanguage()
        
        return self.template()    
    
    def objToTranslate(self):
        return self.group.getTranslation(self.langchangeto)

    def mimetypesToRenderInTranslationForm(self):
        return ('text/html',)        
    
class CreateTranslation(BrowserView):

    def _setCanonicalLanguage(self, obj):
        """Make sure an object has a language set (ie is not neutral).
        """
        lang=obj.Language()
        if not lang:
            portal_state=getMultiAdapter((self.context, self.request),
                                    name="plone_portal_state")
            lang=portal_state.language()
            obj.setLanguage(lang)



    def nextUrl(self, trans):
        """Figure out where users should go after creating the translation.
        """
        try:
            action=trans.getTypeInfo().getActionInfo("object/translate",
                    object=trans)
            return action["url"]
        except ValueError:
            pass

        try:
            action=trans.getTypeInfo().getActionInfo("object/edit",
                    object=trans)
            return action["url"]
        except ValueError:
            pass

        state=getMultiAdapter((trans, self.request), name="plone_context_state")
        return state.view_url()


    def __call__(self):
        status=IStatusMessage(self.request)
        self._setCanonicalLanguage(self.context)

        newlang=self.request["newlanguage"]

        lt=getToolByName(self.context, "portal_languages")
        lt.setLanguageCookie(newlang)
        group = ITranslationGroupLookup(self.context)

        if group.hasTranslation(newlang):
#            state=getMultiAdapter((self.context, self.request),
#                                    name="plone_context_state")
            status.addStatusMessage(_(u"message_translation_exists",
                                        default=u"Translation already exists"),
                                    type="info")
        else:
            group.addTranslation(newlang, self.context)
            status.addStatusMessage(_(u"message_translation_created",
                                      default=u"Translated created."),
                                    type="info")
        trans=group.getTranslation(newlang)

        return self.request.response.redirect(self.nextUrl(trans))




        
